<template>
  <div class="contest-container">
    <!-- Loading 效果覆盖层 -->

    <div v-if="loading" class="loading-overlay">
      <a-spin :size="50" />
    </div>

    <!-- 比赛列表视图 -->
    <div v-if="!showDetail" class="contest-list">
      <a-row :gutter="[20, 20]">
        <a-col :span="12" v-for="contest in contests" :key="contest.id">
          <a-card class="contest-card" :bordered="false">
            <div class="contest-image">
              <img
                :src="
                  contest.coverUrl
                    ? contest.coverUrl
                    : require('@/assets/创建编程竞赛封面.png')
                "
                alt="contest image"
              />
            </div>
            <div class="contest-content">
              <div class="contest-creator">
                <a-avatar :size="40" :image-url="contest.creatorAvatar" />
                <div class="creator-info">
                  <span class="creator-name">{{ contest.creatorName }}</span>
                  <span class="create-time"
                    >创建于 {{ formatDate(contest.createTime || "") }}</span
                  >
                </div>
              </div>
              <h3 class="contest-title">{{ contest.title }}</h3>
              <div class="contest-info">
                <div class="info-item">
                  <icon-calendar /> 开始时间：{{ contest.startTime }}
                </div>
                <div class="info-item">
                  <icon-clock-circle /> 持续时间：{{ contest.duration }}分钟
                </div>
              </div>
              <div class="contest-status">
                <a-tag :color="contest.status === '已结束' ? 'red' : 'green'">
                  {{ contest.status }}
                </a-tag>
                <a-button
                  type="text"
                  class="detail-btn"
                  @click="showContestDetail(contest)"
                >
                  查看详情
                </a-button>
              </div>
            </div>
          </a-card>
        </a-col>
      </a-row>
      <div class="load-more-wrapper">
        <a-button
          class="load-more-btn"
          @click="handleLoadMore"
          :loading="loading"
        >
          加载更多
        </a-button>
      </div>
    </div>

    <!-- 比赛详情视图 -->
    <div v-else class="contest-detail">
      <a-card :bordered="false" class="detail-card">
        <div class="page-header">
          <a-button class="back-btn" @click="showDetail = false">
            <icon-left />返回
          </a-button>
          <h2 class="page-title">{{ currentContest.title }}</h2>
        </div>

        <div class="contest-main-content">
          <div class="basic-info-section">
            <div class="creator-info">
              <a-avatar :size="36" :image-url="currentContest.creatorAvatar" />
              <span class="creator-name">{{ currentContest.creatorName }}</span>
              <span class="create-time"
                >创建于 {{ formatDate(currentContest.createTime) }}</span
              >
            </div>
          </div>

          <div class="info-grid">
            <div class="info-card">
              <icon-team class="info-icon" />
              <div class="info-content">
                <span class="info-label">参与人数</span>
                <span class="info-value">
                  {{ currentContest.participantCount }} 人/
                  {{ currentContest.participantLimit }}人
                </span>
              </div>
            </div>
            <div class="info-card">
              <icon-calendar class="info-icon" />
              <div class="info-content">
                <span class="info-label">开始时间</span>
                <span class="info-value">{{ currentContest.startTime }}</span>
              </div>
            </div>
            <div class="info-card">
              <icon-clock-circle class="info-icon" />
              <div class="info-content">
                <span class="info-label">持续时间</span>
                <span class="info-value"
                  >{{ currentContest.duration }}分钟</span
                >
              </div>
            </div>
          </div>

          <div class="rank-section" v-if="currentContest.status !== '未开始'">
            <h3 class="section-title">排行榜</h3>
            <a-select
              v-model="selectedLimit"
              :style="{ width: '160px' }"
              placeholder="显示人数"
              class="limit-select"
            >
              <a-option :value="2">显示2条</a-option>
              <a-option :value="5">显示5条</a-option>
              <a-option :value="10">显示10条</a-option>
              <a-option :value="20">显示20条</a-option>
              <a-option :value="100">显示全部</a-option>
            </a-select>
            <div class="rank-table-wrapper">
              <a-table
                :columns="columns"
                :data="participants"
                :pagination="false"
                :bordered="{ cell: true }"
                :stripe="true"
                class="custom-rank-table"
              >
                <!-- 修改排名列为索引形式 -->
                <template #rank="{ rowIndex }">
                  <div class="rank-cell" :class="getRankClass(rowIndex + 1)">
                    {{ rowIndex + 1 }}
                  </div>
                </template>

                <template #username="{ record }">
                  <div class="username-cell">
                    <a-avatar :size="24" :image-url="record.avatar" />
                    <a-link>{{ record.name }}</a-link>
                  </div>
                </template>

                <template #score="{ record }">
                  <div class="score-cells">
                    <span class="score-item">
                      {{ record.totalScore }}
                    </span>
                  </div>
                </template>
              </a-table>
            </div>
          </div>

          <div class="action-area">
            <a-button
              type="primary"
              size="large"
              class="join-button"
              @click="handleJoinContest"
              v-if="currentContest.status === '未开始'"
            >
              报名参加
            </a-button>
          </div>
        </div>
      </a-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, h } from "vue";
import type { TableColumnData } from "@arco-design/web-vue";
import { formatDate } from "@/utils/dateUtil";
import { CompetitionControllerService } from "../../../generatedCom/services/CompetitionControllerService";
// import { CompetitionAddRequest } from "../../../generatedCom/models/CompetitionAddRequest";
import { Message } from "@arco-design/web-vue";
const showDetail = ref(false);
const currentContest = ref<any>({});
// 添加选择器响应式变量
const selectedLimit = ref(2);
// 倒计时数据
const countdown = reactive({
  show: true,
  days: 0,
  hours: 0,
  minutes: 0,
  seconds: 0,
});

// 倒计时计算
let timer: number;
const calculateCountdown = () => {
  const targetDate = new Date("2024-03-20 19:00:00").getTime();
  const now = new Date().getTime();
  const distance = targetDate - now;

  if (distance < 0) {
    countdown.show = false;
    clearInterval(timer);
    return;
  }

  countdown.days = Math.floor(distance / (1000 * 60 * 60 * 24));
  countdown.hours = Math.floor(
    (distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
  );
  countdown.minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  countdown.seconds = Math.floor((distance % (1000 * 60)) / 1000);
};

onMounted(async () => {
  await getContests();
  calculateCountdown();
  timer = window.setInterval(calculateCountdown, 1000);
});
const size = ref(5);
const handleLoadMore = async () => {
  console.log("加载更多");
  size.value += 5;
  await getContests();
};

onUnmounted(() => {
  clearInterval(timer);
});

const contests = ref();
// 新增 loading 状态
const loading = ref(true);
const getContests = async () => {
  const res = await CompetitionControllerService.loadCompetitionUsingPost({
    size: size.value,
  });

  console.log(res);
  contests.value = res.data.competitions;

  // const result = await
  loading.value = false;
};
const columns: TableColumnData[] = [
  {
    title: "排名",
    slotName: "rank",
    width: 5,
    align: "center",
  },
  {
    title: "用户ID",
    dataIndex: "userId",
    width: 10,
  },
  {
    title: "用户名",
    slotName: "username",
    width: 20,
  },
  {
    title: "分数",
    slotName: "score",
    width: 180,
    align: "left",
  },
];

const participants = ref([]);

const showContestDetail = async (contest: any) => {
  console.log(contest);
  const res = await CompetitionControllerService.loadRegisterCountUsingPost({
    id: contest.id,
  });
  const result = await CompetitionControllerService.getChartsUsingPost({
    id: contest.id,
    size: selectedLimit.value,
  });
  participants.value = result.data.charts;
  console.log(res);
  currentContest.value = contest;
  currentContest.value.participantCount = res.data;
  showDetail.value = true;
};

const handleJoinContest = async () => {
  // 处理报名逻辑
  console.log("报名");
  const res = await CompetitionControllerService.registerCompetitionUsingPost({
    id: currentContest.value.id,
  });
  console.log(res);
  if (res.code === 0) {
    const res = await CompetitionControllerService.loadRegisterCountUsingPost({
      id: currentContest.value.id,
    });

    console.log(res);
    currentContest.value.participantCount = res.data;
    Message.success("报名成功");
  } else {
    Message.error("报名失败" + res.message);
  }
};

// 修改排名样式方法
const getRankClass = (index: number) => {
  if (index === 1) return "rank-first";
  if (index === 2) return "rank-second";
  if (index === 3) return "rank-third";
  return "";
};
</script>

<style scoped>
.score-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  padding: 8px;
  background: var(--color-fill-1);
  border-radius: 6px;
  transition: all 0.3s;
}

.score-icon {
  color: var(--color-warning-6);
  font-size: 14px;
}

.score-value {
  font-weight: 600;
  font-size: 16px;
}

.score-unit {
  font-size: 12px;
  color: var(--color-text-3);
}

/* 优化已有样式 */
.rank-table :deep(.arco-table-th) {
  background: var(--color-fill-1) !important; /* 确保背景色可见 */
  color: var(--color-text-1); /* 确保文字颜色可见 */
  font-weight: 500;
  text-align: left !important; /* 确保文字左对齐 */
  white-space: nowrap; /* 防止换行 */
  padding: 8px 16px; /* 增加内边距 */
}

.rank-table :deep(.arco-table-tr) {
  transition: background 0.3s;
}

.rank-table :deep(.arco-table-tr:hover) {
  background: var(--color-fill-1);
}
.custom-rank-table :deep(.arco-table-th) {
  background: var(--color-fill-1) !important;
  color: var(--color-text-1);
  font-weight: 500;
  text-align: left !important; /* 强制设置左对齐 */
  white-space: nowrap;
  padding: 8px 16px;
}

.custom-rank-table :deep(.arco-table-cell-score) {
  text-align: left !important;
}

/* 添加分数动画 */
@keyframes score-pop {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
  100% {
    transform: scale(1);
  }
}

.score-cell:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  animation: score-pop 0.4s ease;
}
/* 基础容器样式 */
.contest-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

/* 比赛列表样式 */
.contest-list {
  margin-top: -30px;
}

.contest-card {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border-radius: 12px;
  overflow: hidden;
  background: var(--color-bg-2);
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
}

.contest-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
}

.contest-image {
  height: 160px;
  background: var(--color-fill-2);
  border-radius: 8px;
  margin-bottom: 16px;
  overflow: hidden;
}

.contest-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.contest-creator {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.creator-info {
  margin-left: 12px;
}

.creator-name {
  font-weight: 500;
  color: var(--color-text-1);
}

.create-time {
  font-size: 12px;
  color: var(--color-text-3);
}

.contest-title {
  font-size: 18px;
  margin: 12px 0;
  color: var(--color-text-1);
  font-weight: 600;
}

.contest-info {
  margin: 16px 0;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 8px 0;
  color: var(--color-text-2);
}

.contest-status {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
}

.detail-btn {
  color: var(--primary-color);
  font-weight: 500;
}

/* 详情页面样式 */
.contest-detail {
  padding: 24px;
  background: var(--color-fill-1);
  min-height: 100vh;
}

.detail-card {
  max-width: 1200px;
  margin: 0 auto;
  background: var(--color-bg-2);
  border-radius: 16px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

.page-header {
  padding: 24px;
  margin-bottom: 24px;
  border-bottom: 1px solid var(--color-border-2);
  display: flex;
  align-items: center;
  gap: 16px;
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: var(--color-text-1);
}

.contest-main-content {
  padding: 0 24px 24px;
}

.basic-info-section {
  margin-bottom: 32px;
  padding: 20px;
  background: var(--color-fill-2);
  border-radius: 12px;
}

.creator-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.creator-name {
  font-size: 16px;
  font-weight: 500;
  color: var(--color-text-1);
}

.create-time {
  color: var(--color-text-3);
  margin-left: auto;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 24px;
  margin-bottom: 40px;
}

.info-card {
  padding: 24px;
  background: var(--color-bg-2);
  border: 1px solid var(--color-border-2);
  border-radius: 12px;
  display: flex;
  align-items: center;
  gap: 16px;
}

.info-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.info-icon {
  font-size: 24px;
  color: var(--color-primary);
}

.info-label {
  font-size: 14px;
  color: var(--color-text-3);
}

.info-value {
  font-size: 20px;
  font-weight: 600;
  color: var(--color-text-1);
}

.rank-section {
  margin-top: 40px;
}

.section-title {
  font-size: 20px;
  font-weight: 500;
  margin-bottom: 20px;
  color: var(--color-text-1);
}

.rank-table-wrapper {
  background: var(--color-bg-2);
  border-radius: 12px;
  overflow: hidden;
  border: 1px solid var(--color-border-2);
}

.rank-cell {
  width: 30px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 500;
  background: var(--color-fill-2);
  color: var(--color-text-2);
} /* 确保分数列的内容也左对齐 */
.rank-table :deep(.arco-table-cell-score) {
  text-align: left !important;
}
.rank-first {
  background: linear-gradient(135deg, #ffd700, #ffcc00);
  color: #fff;
}

.rank-second {
  background: linear-gradient(135deg, #c0c0c0, #a0a0a0);
  color: #fff;
}

.rank-third {
  background: linear-gradient(135deg, #cd7f32, #b56c22);
  color: #fff;
}

.username-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.score-cells {
  display: flex;
  gap: 8px;
}

.score-item {
  color: var(--color-text-1);
  font-size: 14px;
  white-space: nowrap;
}

.score-accepted {
  background: var(--color-success-light-1);
  color: var(--color-success-6);
  font-weight: 500;
}

/* 报名按钮 */
.join-button {
  width: 200px;
  height: 48px;
  border-radius: 24px;
  font-size: 16px;
  margin: 32px auto;
  display: block;
  transition: all 0.3s;
}
/* Loading 效果样式 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .contest-card {
    margin: 8px;
  }

  .contest-detail {
    padding: 16px;
  }

  .info-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .page-header {
    padding: 16px;
  }

  .contest-main-content {
    padding: 0 16px 16px;
  }
}
/* 新增的加载更多按钮样式 */
.load-more-wrapper {
  text-align: center;
  margin: 20px 0;
}

.load-more-btn {
  background-color: var(--color-primary);
  color: white;
  border-radius: 20px;
  padding: 8px 32px;
  transition: all 0.3s ease;
}

.load-more-btn:hover {
  background-color: var(--color-primary-light-2);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.load-more-btn:active {
  transform: translateY(0);
}
/* 添加下拉框样式 */
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.limit-select {
  margin-left: auto;
}

/* 调整排名单元格样式 */
.rank-cell {
  font-weight: 600;
  background: var(--color-fill-1);
  transition: all 0.3s;
}

.rank-cell:hover {
  transform: scale(1.1);
}

/* 优化排名颜色样式 */
.rank-first {
  background: linear-gradient(135deg, #ffd700, #ffcc00);
  color: #ffffff;
  box-shadow: 0 2px 4px rgba(255, 215, 0, 0.2);
}

.rank-second {
  background: linear-gradient(135deg, #c0c0c0, #a0a0a0);
  color: #ffffff;
  box-shadow: 0 2px 4px rgba(192, 192, 192, 0.2);
}

.rank-third {
  background: linear-gradient(135deg, #cd7f32, #b56c22);
  color: #ffffff;
  box-shadow: 0 2px 4px rgba(205, 127, 50, 0.2);
}

/* 添加过渡动画 */
.rank-table :deep(.arco-table-tr) {
  transition: transform 0.3s ease;
}

.rank-table :deep(.arco-table-tr:hover) {
  transform: translateX(4px);
}
</style>
